<?php
/**
 * 泉鸣短信接口SDK
 * author:安然_
 * 文件所属项目:QDC SMS SDK
 * 适用API版本：V1//Beta
 * 官网：dev.quanmwl.com
 * 发布日期:2022-8-1
 * 提示：因zkey短信机制原因，我们强烈建议您通过控制台中链接，加入官方QQ群，以便及时更新新版SDK，取得新规则下的正则
*/

namespace Niaoyun\Common\Sms;

class QuanmSmsSDK extends BaseSms implements ISms
{
    //开放平台openId
    private $appId;
    //开放平台apiKey
    private $apiKey;
    //开放平台接口地址
    private $apiUrl;
    //开放平台短信模板ID
    private $templateId;

    public function __construct($appId, $apiKey, $apiUrl, $templateId)
    {

        $this->appId = '修改为自己的OpenID';  // 控制台 （A1轮测试中需要向官方群群主申请开通获取）
        $this->apiKey = '修改为自己的ApiKey'; // 控制台-能力管理-短信接口(SMS) （A1轮测试中需要向官方群群主申请开通获取）
        $this->apiUrl = 'http://dev.quanmwl.com/';
        $this->templateId = '0';  // 平台申请到的模板ID （A1轮测试中需要向官方群群主申请开通获取）
    }


    public function send($tel, $content, $id = null, $type = 2, $param = [], $handleResult = true)
    {
        preg_match('/\d+/', $content, $number);
        $data = [
            'openID' => $this->appId,
            'tel' => $tel,
            'sign' => $this->generateSign($tel),
            'model_id' => $this->templateId,
            'model_args' => json_encode(['code' => $number[0]])
        ];
        $result = $this->curlPost('v1/sms', $data);
        if ($result['state'] = 200) {
            return true;
        } else {
            return false;
        }
    }


    private function generateSign($mobile)
    {
        return md5('sign-' . $this->appId . $this->apiKey . $mobile);
    }

    private function curlPost($path, $body)
    {
        $curl = curl_init();
        $resquest_api = $this->apiUrl . $path;
        curl_setopt($curl, CURLOPT_URL, $resquest_api);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_NOBODY, FALSE);
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);

    }

}